package io.chenglicun.modules.knowledge.service.impl;

import com.dtflys.forest.Forest;
import com.dtflys.forest.http.ForestResponse;
import io.chenglicun.common.page.PageData;
import io.chenglicun.common.utils.Result;
import io.chenglicun.common.utils.SysParamsUtils;
import io.chenglicun.modules.knowledge.api.SjcjApi;
import io.chenglicun.modules.knowledge.constants.KnowledgeParams;
import io.chenglicun.modules.knowledge.dto.UploadRespDTO;
import io.chenglicun.modules.knowledge.service.KnowledgeFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;


@Service
public class KnowledgeFileServiceImpl implements KnowledgeFileService {

    @Value("${knowledge.url}")
    private String knowledgeUrl;

    @Autowired
    private SjcjApi sjcjApi;

    @Override
    public PageData<UploadRespDTO> page(Map<String, Object> params) {
        Long deptId = SysParamsUtils.getLong(KnowledgeParams.KNOWLEDGE_DEPT_ID);
        params.put("deptId", deptId);
        ForestResponse<Result<PageData<UploadRespDTO>>> page = sjcjApi.page(params);
        if (page.isSuccess() && page.getResult().success()) {
            return page.getResult().getData();
        }
        return null;
    }

    @Override
    public void delete(Long[] ids) {
        ForestResponse<Result> delete = sjcjApi.delete(ids);
    }

    @Override
    public void upload(MultipartFile multipartFile) throws IOException {
        Long deptId = SysParamsUtils.getLong(KnowledgeParams.KNOWLEDGE_DEPT_ID);
        InputStream inputStream = multipartFile.getInputStream();
        Forest.post(knowledgeUrl + "/xunfeiUpload?deptId=" + deptId)
                // 指定请求体为Multipart格式
                .contentTypeMultipartFormData()
                // 添加File对象
                .addFile("file", inputStream, multipartFile.getOriginalFilename()).execute();
        inputStream.close();
    }
}
